<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="商品名称">
            <a-input v-decorator="['productName']" placeholder="请输入商品名称"/>
          </a-form-item>
          <a-form-item label="商品编码">
            <a-input v-decorator="['spu']" placeholder="请输入商品编码"/>
          </a-form-item>
          <a-form-item label="商品品牌">
            <a-select
                v-decorator="['brandNo']"
                :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
                :options="brandList"
                allowClear
                placeholder="请输入商品品牌"
            ></a-select>
          </a-form-item>
          <a-form-item label="商品类目">
            <a-tree-select
                v-decorator="['catNo']"
                :treeData="categoryListTree"
                :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
                allowClear
                placeholder="请选择商品类目"
            ></a-tree-select>
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button class="mr-15" html-type="submit" icon="search" type="primary">搜索</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </a-row>
      <!-- 操作板块 -->
      <div class="row-item-tab clearfix">
        <div class="tab-list fl-l">
          <a-radio-group :defaultValue="queryParam.status" @change="handleTabs">
            <a-radio-button v-for="(item, index) in StatusEnum.data" :key="index" :value="item.key">
              {{ item.name }}
            </a-radio-button>
          </a-radio-group>
        </div>
        <a-button
            v-if="$auth('/product/create')"
            class="fl-l"
            type="primary"
            icon="plus"
            @click="handleCreate()"
        >创建商品
        </a-button>
        <div v-if="selectedRowKeys.length" class="button-group">
          <a-button-group class="ml-10">
            <a-button
                v-action:status
                icon="arrow-up"
                @click="handleUpdateStatus(selectedRowKeys, StatusEnum.ENABLED.key)"
            >启用
            </a-button>
            <a-button
                v-action:status
                icon="arrow-down"
                @click="handleUpdateStatus(selectedRowKeys,  StatusEnum.DISABLED.key)"
            >禁用
            </a-button>
            <a-button v-action:delete icon="delete" @click="handleDelete(selectedRowKeys)">删除</a-button>
          </a-button-group>
        </div>
      </div>
    </div>
    <s-table
        ref="table"
        :scroll="{ x: 1300 }"
        :loading="isLoading"
        :columns="columns"
        :data="loadData"
        :rowSelection="rowSelection"
        :pageSize="15"
        rowKey="spu"
    >
      <!-- 商品图片 -->
      <template v-slot:images="text">
        <a :href="getMain(text)" target="_blank" title="点击查看原图">
          <img :src="getMain(text)" alt="商品图片" height="50" width="50"/>
        </a>
      </template>
      <!-- 商品名称 -->
      <template v-slot:cat="text, item">
        <p>{{ [item.catRootName, item.catParentName, item.catName].filter(Boolean).join('->') }}</p>
      </template>
      <!-- 商品状态 -->
      <template v-slot:status="text, item">
        <a-tag
            class="cur-p"
            :color="text === StatusEnum.ENABLED.key ? 'green' : 'red'"
            @click="handleUpdateStatus([item.spu], text !== StatusEnum.ENABLED.key ? StatusEnum.ENABLED.key : StatusEnum.DISABLED.key)"
        >
          {{ text === StatusEnum.ENABLED.key ? StatusEnum.ENABLED.name : StatusEnum.DISABLED.name }}
        </a-tag>
      </template>
      <!-- 操作项 -->
      <template v-slot:action="text, item" class="actions">
        <router-link
            v-if="$auth('/product/update')"
            :to="{ path: '/product/update', query: { spu: item.spu } }"
        >编辑
        </router-link>
        <a v-action:delete @click="handleDelete([item.spu])">删除</a>
      </template>
    </s-table>
    <a-modal
        :confirmLoading="confirmLoading"
        :destroyOnClose="true"
        :maskClosable="false"
        :visible="visible"
        :width="720"
        title="选择商品分类"
        @cancel="handleCancel"
        @ok="handleSubmit"
    >
      <a-spin :spinning="confirmLoading">
        <a-form :form="modalForm">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品类型">
            <a-radio-group
                v-decorator="['type', { initialValue: CategoryType.PHYSICAL.key, rules: [{ required: true }] }]">
              <a-radio
                  v-for="(item, index) in CategoryType.data"
                  :key="index"
                  :value="item.key"
                  @change="handleChangeType"
              >
                {{ item.name }}
              </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="选择分类">
            <a-cascader
                v-decorator="['catNo', { rules: [{ required: true, message: '选择分类' }] }]"
                :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
                :options="categoryListTree"
                placeholder="选择分类"
            >
            </a-cascader>
          </a-form-item>
          <!--  todo 添加常用分类  -->
        </a-form>
      </a-spin>
    </a-modal>
  </a-card>
</template>

<script>
import * as ProductApi from '@/api/product'
import * as BrandApi from '@/api/brand'
import {ContentHeader, STable} from '@/components'
import {getMain} from '@/common/enum/product/ImageType'
import StatusEnum from '@/common/enum/Status'
import CategoryModel from '@/common/model/Category'
import {CategoryTypeEnum} from '@/common/enum/product'

// 表格表头
const columns = [
  {
    title: '商品图片',
    dataIndex: 'images',
    scopedSlots: {customRender: 'images'}
  },
  {
    title: 'spu',
    dataIndex: 'spu',
  },
  {
    title: '商品名称',
    dataIndex: 'productName',
  },
  {
    title: '品牌名称',
    dataIndex: 'brandName'
  },
  {
    title: '商品类目',
    dataIndex: 'cat',
    scopedSlots: {customRender: 'cat'}
  },
  {
    title: '库存总量',
    dataIndex: 'stockTotal'
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: {customRender: 'status'}
  },
  {
    title: '添加时间',
    dataIndex: 'creationTime'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    scopedSlots: {customRender: 'action'}
  }
]

export default {
  name: 'Index',
  components: {
    ContentHeader,
    STable
  },
  data() {
    return {
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      // 商品分类列表
      categoryListTree: [],
      brandList: [],
      // 查询参数
      queryParam: {
        status: StatusEnum.ENABLED.key,
      },
      // 正在加载
      isLoading: false,
      // 表头
      columns,
      // 选择的元素
      selectedRowKeys: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return ProductApi.list({...param, ...this.queryParam})
      },
      // 标签布局属性
      labelCol: {
        span: 7
      },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前弹窗表单元素
      modalForm: this.$form.createForm(this)
    }
  },
  created() {
    // 默认的查询参数
    if (this.$route.query.status) {
      this.queryParam.status = this.$route.query.status
    }
    // 获取商品分类列表
    this.getCategoryList()
    this.getBrandList()
  },
  computed: {
    CategoryType() {
      return CategoryTypeEnum
    },
    StatusEnum() {
      return StatusEnum
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    getMain,

    // 选中项发生变化时的回调
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    // 切换tab
    handleTabs(e) {
      this.queryParam.status = e.target.value
      this.handleRefresh(true)
    },

    // 确认搜索
    handleSearch(e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = {...this.queryParam, ...values}
          this.handleRefresh(true)
        }
      })
    },

    // 重置搜索表单
    handleReset() {
      this.searchForm.resetFields()
    },

    // 获取品牌列表
    getBrandList() {
      this.isLoading = true
      BrandApi.options()
          .then(result => {
            this.brandList = result
          })
          .finally(() => this.isLoading = false)
    },

    // 获取分类列表
    getCategoryList() {
      this.isLoading = true
      CategoryModel.getListFromScreen()
          .then(result => {
            this.categoryListTree = result
          })
          .finally(() => this.isLoading = false)
    },

    // 修改商品状态(启用/禁用)
    handleUpdateStatus(spuList, state = StatusEnum.ENABLED.key) {
      if (!this.$auth('/product/index.status')) {
        return false
      }
      this.isLoading = true
      ProductApi.status(state, spuList)
          .then(result => {
            // 显示成功
            this.$message.success('操作成功', 1.5)
            this.handleRefresh()
          })
          .finally(result => {
            this.isLoading = false
          })
    },

    // 删除记录
    handleDelete(spuList) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk() {
          return ProductApi.deleted(spuList)
              .then(result => {
                app.$message.success('操作成功', 1.5)
                app.handleRefresh()
              })
              .finally(result => modal.destroy())
        }
      })
    },

    // 新增记录
    handleCreate() {
      this.visible = true;
    },

    /**
     * 刷新列表
     * @param {Boolean} bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      this.selectedRowKeys = []
      this.$refs.table.refresh(bool)
    },
    handleChangeType(e) {
      CategoryModel.getListFromScreen({type: e.target.value})
          .then(selectList => {
            this.categoryListTree = selectList
          })
    },
    // 确认按钮
    handleSubmit(e) {
      e.preventDefault()
      // 表单验证
      const {modalForm: {validateFields}} = this
      validateFields((errors, values) => {
        // 提交到后端api
        if (!errors) {
          this.onFormSubmit(values)
        }
      })
      // 处理选中的值
    },
    // 关闭对话框事件
    handleCancel() {
      this.modalForm.resetFields()
      this.visible = false
    },
    onFormSubmit(values) {
      this.confirmLoading = true
      // 跳转到商品创建页面并携带catNo参数
      this.$router.push({
        path: '/product/create',
        query: {catNo: values.catNo} // 取最后一个分类编号
      }).then(() => {
        // 关闭对话框事件
        this.handleCancel()
      }).finally(result => {
        this.confirmLoading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.ant-card-body {
  padding: 22px 29px 25px;
}

// 筛选tab
.tab-list {
  margin-right: 20px;
}
</style>
